package com.wave.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wave.common.core.domain.PageQuery;
import com.wave.common.core.page.TableDataInfo;
import com.wave.common.utils.StringUtils;
import com.wave.system.domain.SysProductQuery;
import com.wave.system.domain.SysToolBoardTask;
import com.wave.system.domain.bo.SysProductQueryBo;
import com.wave.system.domain.vo.SysProductQueryVo;
import com.wave.system.mapper.SysProductQueryMapper;
import com.wave.system.mapper.SysToolBoardTaskMapper;
import com.wave.system.service.ISysProduceRecordService;
import com.wave.system.service.ISysProductQueryService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 产品查询Service业务层处理
 *
 * @author wave
 * @date 2024-10-12
 */
@RequiredArgsConstructor
@Service
public class SysProductQueryServiceImpl implements ISysProductQueryService {

    private static final Logger log = LoggerFactory.getLogger(SysProductQueryServiceImpl.class);
    private final SysProductQueryMapper baseMapper;
    private final SysToolBoardTaskMapper toolBoardTaskMapper;
    private final ISysProduceRecordService sysProduceRecordService;

    /**
     * 查询产品查询
     */
    @Override
    public SysProductQueryVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询产品查询列表
     */
    @Override
    public TableDataInfo<SysProductQueryVo> queryPageList(SysProductQueryBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysProductQuery> lqw = buildQueryWrapper(bo);
        Page<SysProductQueryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询产品查询列表
     */
    @Override
    public List<SysProductQueryVo> queryList(SysProductQueryBo bo) {
        LambdaQueryWrapper<SysProductQuery> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysProductQuery> buildQueryWrapper(SysProductQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysProductQuery> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getProductSn()), SysProductQuery::getProductSn, bo.getProductSn());
        lqw.like(StringUtils.isNotBlank(bo.getShelfNumber()), SysProductQuery::getShelfNumber, bo.getShelfNumber());
        lqw.eq(bo.getCompletionTime() != null, SysProductQuery::getCompletionTime, bo.getCompletionTime());
        lqw.eq(bo.getCompletionType() != null, SysProductQuery::getCompletionType, bo.getCompletionType());
        lqw.orderByDesc(SysProductQuery::getCompletionTime);
        return lqw;
    }

    /**
     * 新增产品查询
     */
    @Override
    public Boolean insertByBo(SysProductQueryBo bo) {
        SysProductQuery add = BeanUtil.toBean(bo, SysProductQuery.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改产品查询
     */
    @Override
    public Boolean updateByBo(SysProductQueryBo bo) {
        // 页面点手动完成触发，给完成时间和完成类型赋值
        bo.setCompletionTime(new Date());
        bo.setCompletionType(1);
        SysProductQuery update = BeanUtil.toBean(bo, SysProductQuery.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysProductQuery entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除产品查询
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    /**
     * 更新产品查询信息和工装板任务信息
     *
     * @param snCode
     * @param taskStatus
     * @param completeType
     */
    @Override
    @Transactional
    public void updateTaskQueryInfo(String snCode, String taskStatus, String shelfNumber, Integer completeType) {
        log.info("开始更新物料码snCode:{},taskStatus:{}，completeType:{}", snCode, taskStatus, completeType);
        LambdaUpdateWrapper<SysProductQuery> query = new LambdaUpdateWrapper<>();
        query.set(SysProductQuery::getCompletionTime, new Date());
        query.set(SysProductQuery::getCompletionType, completeType);
        query.set(SysProductQuery::getShelfNumber, shelfNumber);
        query.eq(SysProductQuery::getProductSn, snCode);
        int updateSuccess = baseMapper.update(query);
        if (updateSuccess > 0) {
            log.info("物料码:{}更新产品查询信息成功", snCode);
        }
        LambdaUpdateWrapper<SysToolBoardTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SysToolBoardTask::getTaskStatus, taskStatus);
        updateWrapper.set(SysToolBoardTask::getUpdateTime, new Date());
        updateWrapper.eq(SysToolBoardTask::getProductSn, snCode);
        int updateTaskSuccess = toolBoardTaskMapper.update(updateWrapper);
        if (updateTaskSuccess > 0) {
            log.info("物料码:{}更新工装板任务状态成功", snCode);
        }
        List<String> list = Collections.singletonList(snCode);
        Boolean saveSuccess = sysProduceRecordService.batchSaveBySnCodes(list, shelfNumber);
        if (saveSuccess) {
            log.info("物料码:{}插入生产记录成功", snCode);
        }
        log.info("物料码snCode:{},更新任务状态、产品查询信息，保存生产记录结束", snCode);
    }

    @Override
    public void deleteQueryInfoBySnCode(String productSn) {
        LambdaQueryWrapper<SysProductQuery> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysProductQuery::getProductSn, productSn);
        baseMapper.delete(queryWrapper);
    }
}
